In C, storage classes are used to determine the lifetime, scope, and visibility of variables and functions in a program. There are four main storage classes in C:
auto: The auto storage class is the default storage class for local variables. It is rarely used explicitly since local variables are automatically given this storage class.
register: The register storage class is used to suggest the compiler to store a variable in a CPU register for faster access. Hover, modern compilers automatically optimize register allocation, so this storage class is rarely used.
static: The static storage class is used to create variables or functions with static storage duration. Variables declared as static retain their values between function calls, and functions declared as static are only visible within the current source file.
extern: The extern storage class is used to declare a variable or function that is defined in another file. It indicates that the actual definition exists elsewhere, allowing access to variables or functions defined in separate source files.
#include <stdio.h>
// Global variable with static storage duration
static int staticVar = 10;
// Function declaration
void function1();
// Function definition
void function2() {
// Automatic variable with auto storage class (default for local variables)
auto int localVar = 5;
printf("Local variable in function2: %d\n", localVar);
printf("Static variable in function2: %d\n", staticVar);
// Call function1
function1();
}
// Function definition for function1
void function1() {
// Static variable inside function1 retains its value across function calls
static int staticFuncVar = 0;
printf("Static function variable in function1: %d\n", staticFuncVar);
staticFuncVar++;
}
// External global variable (defined in another file)
extern int globalVar;
int main() {
// Call function2
function2();
// Access external global variable defined in another file
printf("Global variable: %d\n", globalVar);
return 0;
}
Local variable in function2: 5
Static variable in function2: 10
Static function variable in function1: 0
Global variable: 42
What is the storage class that allocates memory for a variable once for the entire program?
What storage class is used for function parameters and local variables that are temporary in nature?
Which storage class specifies that a variable is stored in the CPU registers for faster access?
What storage class is used to declare a variable that can be accessed by other files as well?
What is the storage class that allocates memory every time a function is called and releases it upon return?